import { MES_LXK_ApiHost } from '@/utils/Interceptors'

// 产品信息接口
export interface Product {
  id: number
  productId: number
  productName: string
  productNumber: string
  productSpecification: string
  inventoryUnit: string
  productAttribute?: string
  processRoute?: string
  maxInventory: number
  minInventory: number
  safetyInventory: number
  num: number
  current: number
  createdTime: string
  createdBy: string
  modifiedBy: string | null
  modifiedTime: string | null
  isDelete: boolean
}

// 出库单明细接口
export interface OutboundOrderDetail {
  id?: number
  outboundOrderNumber: string
  productId: number
  currentInventoryQuantity: number
  outboundQuantity: number
  productName: string
  productNumber: string
  productSpecification: string
  inventoryUnit: string
  maxInventory: number
  minInventory: number
  safetyInventory: number
  inventoryQuantity: number
  createdTime?: string
  createdBy?: string
  modifiedTime?: string | null
  modifiedBy?: string | null
  isDelete?: boolean
}

// 出库单数据接口
export interface OutboundOrder {
  outboundId: number
  outboundOrderNumber: string
  outboundType: string
  outboundTime: string
  approval: string  // 修正：后端返回的是小写 approval
  remarks: string
  bkThumbnail?: string  // 缩略图
  annex?: string        // 附件
  createdTime: string
  createdBy: string
  modifiedBy: string
  modifiedTime: string
  isDelete: boolean
  details?: OutboundOrderDetail[]
}

// API响应接口
export interface ApiResponse<T> {
  code: number
  msg: string
  data: T
}

// 搜索参数接口
export interface SearchParams {
  startTime?: string
  endTime?: string
  outboundOrderNumber?: string
  outboundType?: string
  approval?: string  // 修正：后端使用小写 approval
  createdBy?: string
}

// 新增出库单参数接口
export interface AddOutboundOrderParams {
  outboundId: number
  outboundOrderNumber: string
  outboundType: string
  outboundTime: string
  approval: string  // 修正：后端使用小写 approval
  remarks: string
  bkThumbnail?: string  // 缩略图
  annex?: string        // 附件
  createdTime: string
  createdBy: string
  modifiedBy: string
  modifiedTime: string
  isDelete: boolean
}

// 获取所有出库单
export const getAllOutboundOrders = async (forceRefresh = false): Promise<ApiResponse<OutboundOrder[]>> => {
  try {
    const params = forceRefresh ? { _t: Date.now() } : {}
    console.log('获取出库单参数:', params)
    
    const response = await MES_LXK_ApiHost.get('/api/OutboundOrder/GetAll', { params })
    console.log('获取出库单响应:', response.data)
    return response.data
  } catch (error) {
    console.error('获取出库单失败:', error)
    throw error
  }
}

// 根据ID获取出库单
export const getOutboundOrderById = async (id: number): Promise<ApiResponse<OutboundOrder>> => {
  try {
    const response = await MES_LXK_ApiHost.get(`/api/OutboundOrder/GetById/${id}`)
    return response.data
  } catch (error) {
    console.error('获取出库单失败:', error)
    throw error
  }
}

// 搜索出库单
export const searchOutboundOrders = async (params: SearchParams): Promise<ApiResponse<OutboundOrder[]>> => {
  try {
    // 过滤掉空值参数
    const filteredParams = Object.fromEntries(
      Object.entries(params).filter(([_, value]) => value !== undefined && value !== '')
    )
    
    const response = await MES_LXK_ApiHost.get('/api/OutboundOrder/GetAll', {
      params: filteredParams
    })
    return response.data
  } catch (error) {
    console.error('搜索出库单失败:', error)
    throw error
  }
}

// 获取产品列表
export const getProducts = async (): Promise<ApiResponse<Product[]>> => {
  try {
    // 尝试多个可能的API路径
    const possiblePaths = [
      '/api/ProductDetail/GetAll',
      '/api/Product/GetAll',
      '/api/ProductDetail/GetAllProductDetails',
      '/api/Product/GetAllProducts'
    ]
    
    let lastError = null
    
    for (const path of possiblePaths) {
      try {
        console.log('尝试API路径:', path)
        const response = await MES_LXK_ApiHost.get(path)
        console.log('API调用成功:', path, response.data)
        return response.data
      } catch (error: any) {
        console.log('API路径失败:', path, error.response?.status)
        lastError = error
        continue
      }
    }
    
    // 如果所有路径都失败，抛出最后一个错误
    throw lastError
  } catch (error) {
    console.error('获取产品列表失败:', error)
    throw error
  }
}

// 获取出库单明细（按出库单号）
export const getOutboundOrderDetails = async (
  outboundOrderNumber: string
): Promise<ApiResponse<any[]>> => {
  try {
    const response = await MES_LXK_ApiHost.get(
      `/api/OutboundOrder/GetProductDetails/${outboundOrderNumber}`
    )
    return response.data
  } catch (error) {
    console.error('获取出库单明细失败:', error)
    throw error
  }
}

// 获取出库单明细（查询参数方式）
export const getOutboundOrderDetailsByQuery = async (
  outboundOrderNumber: string
): Promise<ApiResponse<any[]>> => {
  try {
    const response = await MES_LXK_ApiHost.get('/api/OutboundOrder/GetProductDetails', {
      params: { outboundOrderNumber }
    })
    return response.data
  } catch (error) {
    console.error('获取出库单明细失败:', error)
    throw error
  }
}

// 获取出库产品明细列表
export const getOutboundProductDetails = async (): Promise<ApiResponse<OutboundOrderDetail[]>> => {
  try {
    const response = await MES_LXK_ApiHost.get('/api/OutboundProductDetail')
    return response.data
  } catch (error) {
    console.error('获取出库产品明细列表失败:', error)
    throw error
  }
}

// 根据出库单号获取出库产品明细
export const getOutboundProductDetailsByOrderNumber = async (
  outboundOrderNumber: string
): Promise<ApiResponse<OutboundOrderDetail[]>> => {
  try {
    const response = await MES_LXK_ApiHost.get('/api/OutboundProductDetail', {
      params: { outboundOrderNumber }
    })
    return response.data
  } catch (error) {
    console.error('根据出库单号获取产品明细失败:', error)
    throw error
  }
}

// 新增出库单
export const addOutboundOrder = async (params: AddOutboundOrderParams): Promise<ApiResponse<boolean>> => {
  try {
    console.log('新增出库单参数:', params)
    
    const response = await MES_LXK_ApiHost.post('/api/OutboundOrder/Add', params)
    console.log('新增出库单响应:', response.data)
    return response.data
  } catch (error: any) {
    console.error('新增出库单失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
      console.error('错误状态:', error.response.status)
    }
    throw error
  }
}

// 更新出库单
export const updateOutboundOrder = async (params: OutboundOrder): Promise<ApiResponse<boolean>> => {
  try {
    const response = await MES_LXK_ApiHost.put('/api/OutboundOrder/Update', params)
    return response.data
  } catch (error) {
    console.error('更新出库单失败:', error)
    throw error
  }
}

// 删除出库单
export const deleteOutboundOrder = async (id: number): Promise<ApiResponse<boolean>> => {
  try {
    const response = await MES_LXK_ApiHost.delete(`/api/OutboundOrder/Delete/${id}`)
    return response.data
  } catch (error) {
    console.error('删除出库单失败:', error)
    throw error
  }
}

// 更新审核状态
export const updateApprovalStatus = async (params: {
  outboundId: number
  approval: string  // 修正：后端使用小写 approval
  modifiedBy: string
  remarks?: string
}): Promise<ApiResponse<boolean>> => {
  try {
    console.log('调用更新审核状态API，参数:', params)
    console.log('API端点:', '/api/OutboundOrder/UpdateApprovalStatus')
    
    // 根据后端API要求，转换参数格式
    const statusMapping: { [key: string]: number } = {
      '待审核': 0,
      '审核通过': 1,
      '驳回': 2,
      '拒绝': 2,
      '已审核': 1,
      '已拒绝': 2
    }
    
    // 尝试多种请求格式
    const requestFormats = [
      // 格式1：使用数字状态
      {
        outboundId: params.outboundId,
        status: statusMapping[params.approval] || 0,
        approvalComment: params.remarks || '',
        approver: params.modifiedBy
      },
      // 格式2：直接使用字符串状态
      {
        outboundId: params.outboundId,
        approval: params.approval,
        approvalComment: params.remarks || '',
        approver: params.modifiedBy
      },
      // 格式3：使用approvalStatus字段
      {
        outboundId: params.outboundId,
        approvalStatus: params.approval,
        approvalComment: params.remarks || '',
        approver: params.modifiedBy
      }
    ]
    
    let lastError: any = null
    
    // 尝试不同的请求格式
    for (let i = 0; i < requestFormats.length; i++) {
      try {
        const requestData = requestFormats[i]
        console.log(`尝试请求格式 ${i + 1}:`, requestData)
        
        const response = await MES_LXK_ApiHost.put('/api/OutboundOrder/UpdateApprovalStatus', requestData)
        
        console.log(`请求格式 ${i + 1} 响应:`, response.data)
        
        // 检查响应中的状态信息
        if (response.data && response.data.msg) {
          console.log('响应消息:', response.data.msg)
        }
        
        // 如果成功，返回结果
        if (response.data && response.data.code === 200) {
          return response.data
        }
        
        lastError = response.data
      } catch (error: any) {
        console.error(`请求格式 ${i + 1} 失败:`, error)
        lastError = error
        continue
      }
    }
    
    // 如果所有格式都失败，抛出最后一个错误
    throw lastError
  } catch (error: any) {
    console.error('更新审核状态失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
      console.error('错误状态:', error.response.status)
    }
    throw error
  }
}

// 获取审核状态列表
export const getApprovalStatusList = async (): Promise<ApiResponse<string[]>> => {
  try {
    const response = await MES_LXK_ApiHost.get('/api/OutboundOrder/GetApprovalStatusList')
    return response.data
  } catch (error) {
    console.error('获取审核状态列表失败:', error)
    throw error
  }
}

// 获取审核状态选项
export const getApprovalStatusOptions = async (): Promise<ApiResponse<any[]>> => {
  try {
    const response = await MES_LXK_ApiHost.get('/api/OutboundOrder/GetApprovalStatusOptions')
    return response.data
  } catch (error) {
    console.error('获取审核状态选项失败:', error)
    throw error
  }
}

// 测试接口
export const testOutboundOrderApi = async (): Promise<ApiResponse<any>> => {
  try {
    const response = await MES_LXK_ApiHost.get('/api/OutboundOrder/test')
    return response.data
  } catch (error) {
    console.error('测试出库单接口失败:', error)
    throw error
  }
}

// 导出出库单
export const exportOutboundOrders = async (params: SearchParams): Promise<Blob> => {
  try {
    // 过滤掉空值参数
    const filteredParams = Object.fromEntries(
      Object.entries(params).filter(([_, value]) => value !== undefined && value !== '')
    )
    
    const response = await MES_LXK_ApiHost.get('/api/OutboundOrder/Export', {
      params: filteredParams,
      responseType: 'blob'
    })
    return response.data
  } catch (error) {
    console.error('导出出库单失败:', error)
    throw error
  }
}

// 新增出库单明细
export const addOutboundOrderDetail = async (params: any): Promise<ApiResponse<boolean>> => {
  try {
    const response = await MES_LXK_ApiHost.post('/api/OutboundProductDetail', params)
    return response.data
  } catch (error) {
    console.error('新增出库单明细失败:', error)
    throw error
  }
}

// 更新出库单明细
export const updateOutboundOrderDetail = async (params: any): Promise<ApiResponse<boolean>> => {
  try {
    const response = await MES_LXK_ApiHost.put('/api/OutboundProductDetail/Update', params)
    return response.data
  } catch (error) {
    console.error('更新出库单明细失败:', error)
    throw error
  }
}

// 删除出库单明细
export const deleteOutboundOrderDetail = async (id: number): Promise<ApiResponse<boolean>> => {
  try {
    const response = await MES_LXK_ApiHost.delete(`/api/OutboundProductDetail/Delete/${id}`)
    return response.data
  } catch (error) {
    console.error('删除出库单明细失败:', error)
    throw error
  }
}

// 批量新增出库单明细
export const batchAddOutboundOrderDetails = async (details: any[]): Promise<ApiResponse<boolean>> => {
  try {
    const response = await MES_LXK_ApiHost.post('/api/OutboundProductDetail', details)
    return response.data
  } catch (error) {
    console.error('批量新增出库单明细失败:', error)
    throw error
  }
}

// 保存出库单明细
export const saveOutboundOrderDetails = async (
  outboundOrderNumber: string,
  details: any[],
  createdBy: string = 'admin',
  modifiedBy: string = 'admin'
): Promise<ApiResponse<{ okCount: number; failCount: number }>> => {
  try {
    let okCount = 0
    let failCount = 0
    
    // 尝试批量保存
    try {
      const batchPayload = details.map(detail => ({
        outboundOrderNumber: outboundOrderNumber,
        productId: detail.productId,
        currentInventoryQuantity: detail.currentInventoryQuantity || 0,
        outboundQuantity: detail.outboundQuantity || 1,
        productName: detail.productName,
        productNumber: detail.productNumber,
        productSpecification: detail.productSpecification,
        inventoryUnit: detail.inventoryUnit,
        maxInventory: detail.maxInventory,
        minInventory: detail.minInventory,
        safetyInventory: detail.safetyInventory,
        inventoryQuantity: detail.inventoryQuantity || 0,
        createdBy: createdBy,
        modifiedBy: modifiedBy,
        createdTime: new Date().toISOString(),
        modifiedTime: new Date().toISOString(),
        isDelete: false
      }))
      
             console.log('批量保存出库单明细数据:', batchPayload)
       
       const response = await MES_LXK_ApiHost.post('/api/OutboundProductDetail', batchPayload)
      const resp = response.data
      console.log('批量保存出库单明细响应:', resp)
      
      if (resp && resp.code === 200) {
        okCount = details.length
        return { code: 200, msg: '批量保存成功', data: { okCount, failCount } }
      } else {
        failCount = details.length
        console.error('批量保存失败:', resp)
      }
    } catch (batchError) {
      console.warn('批量保存失败，尝试单个保存:', batchError)
      
      // 批量保存失败，尝试单个保存
      for (const detail of details) {
        const payload = {
          outboundOrderNumber: outboundOrderNumber,
          productId: detail.productId,
          currentInventoryQuantity: detail.currentInventoryQuantity || 0,
          outboundQuantity: detail.outboundQuantity || 1,
          productName: detail.productName,
          productNumber: detail.productNumber,
          productSpecification: detail.productSpecification,
          inventoryUnit: detail.inventoryUnit,
          maxInventory: detail.maxInventory,
          minInventory: detail.minInventory,
          safetyInventory: detail.safetyInventory,
          inventoryQuantity: detail.inventoryQuantity || 0,
          createdBy: createdBy,
          modifiedBy: modifiedBy,
          createdTime: new Date().toISOString(),
          modifiedTime: new Date().toISOString(),
          isDelete: false
        }
        
                 console.log('发送单个出库单明细数据:', payload)
         
         try {
           const response = await MES_LXK_ApiHost.post('/api/OutboundProductDetail', payload)
          const resp = response.data
          console.log('单个出库单明细保存响应:', resp)
          if (resp && resp.code === 200) {
            okCount++
          } else {
            failCount++
            console.error('单个保存失败:', resp)
          }
        } catch (error) {
          console.error('单个保存明细失败:', error)
          failCount++
        }
      }
    }
    
    return { code: 200, msg: 'OK', data: { okCount, failCount } }
  } catch (error) {
    console.error('保存出库单明细失败:', error)
    throw error
  }
}

// 上传出库单缩略图
export const uploadOutboundThumbnail = async (file: File): Promise<ApiResponse<{
  success: boolean
  filePath: string
  fileName: string
  fileSize: number
  errorMessage: string | null
}>> => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    
    console.log('开始上传出库单缩略图:', file.name)
    
    const response = await MES_LXK_ApiHost.post('/api/FileUpload/UploadOutboundThumbnail', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    console.log('出库单缩略图上传响应:', response.data)
    
    return response.data
  } catch (error: any) {
    console.error('出库单缩略图上传失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
      console.error('错误状态:', error.response.status)
    }
    throw error
  }
}

// 上传出库单附件
export const uploadOutboundAnnex = async (file: File): Promise<ApiResponse<{
  success: boolean
  filePath: string
  fileName: string
  fileSize: number
  errorMessage: string | null
}>> => {
  try {
    const formData = new FormData()
    formData.append('file', file)
    
    console.log('开始上传出库单附件:', file.name)
    
    const response = await MES_LXK_ApiHost.post('/api/FileUpload/UploadOutboundAnnex', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    console.log('出库单附件上传响应:', response.data)
    
    return response.data
  } catch (error: any) {
    console.error('出库单附件上传失败:', error)
    if (error.response) {
      console.error('错误响应:', error.response.data)
      console.error('错误状态:', error.response.status)
    }
    throw error
  }
}
